package cn.ainit.sys.framework.upload;

import java.awt.image.RenderedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Blob;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import oracle.sql.BLOB;

import org.junit.Test;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


import cn.ainit.sys.utils.UUID32;

@Controller
@RequestMapping("/upload")
public class UploadController {
	
	private UploadService uploadService;
	
	@Resource
	public void setUploadService(UploadService uploadService) {
		this.uploadService = uploadService;
	}
	
	//v2.0.0 //1122
	/***
	 * 新版
	 */
	@RequestMapping("/upW")
	public String openUpWin(UpReceiveParams reParams,HttpServletRequest request, HttpSession session){
		request.setAttribute("params",reParams);
		return "/model/upload/multiUpZone";
	} 
	
	/**
	 * 上传文件 
	 * @param request (  keyValue dsId clnName flag )
	 * @param session
	 * @param response
	 * @return
	 */
	public SysUpReturnMsg upMulFiles(HttpServletRequest request,HttpSession session,HttpServletResponse response){
		SysUpReturnMsg upReturnMsg = new SysUpReturnMsg();
		String flag = request.getParameter("flag"); //flag = 1 图片上传  flag = 2 文件上传
		String keyValue = request.getParameter("keyValue");
		String dsId = request.getParameter("dsId");
		String clnName = request.getParameter("clnName");
		String describe= (String) request.getAttribute("describe");
		String filename= (String) request.getAttribute("name");
		if (filename.lastIndexOf(".") > 0) {
			filename = filename.substring(0, filename.lastIndexOf(".")).toString();
		}
		if ("".equals(filename)) {
			filename = describe;
		}
		String suffix = (String) request.getAttribute("suffix");
		String path = (String) request.getAttribute("path");
		if (keyValue == null || "".equals(keyValue.trim())) {
			keyValue = UUID32.newGuid();
		}
		SysUploadInfo uploadInfo = new SysUploadInfo();
		uploadInfo.setDsId(dsId);
		uploadInfo.setDescribe(describe);
		uploadInfo.setName(filename);
		uploadInfo.setClnName(clnName);
		uploadInfo.setSuffix(suffix);
		uploadInfo.setPath(path);
		uploadInfo.setKeyValue(keyValue);
		uploadInfo.setRequest(request);
		try {
			int dbflag = 2;//flag = 1 将文件保存到服务器本地     flag = 2 将文件保存到数据库
			if(dbflag == 2){
				uploadInfo.setFileid(this.uploadService.saveFilesToDb(uploadInfo));
			}else{
				this.uploadService.saveFiles(uploadInfo);
			}
			upReturnMsg.setUploadInfo(uploadInfo);
			upReturnMsg.setFlag(flag);
			upReturnMsg.setMsg("success");
		} catch (Exception e) {
			e.printStackTrace();
			upReturnMsg.setMsg("fail");
			return upReturnMsg;
		}
		return upReturnMsg;
	}
	
	
	
	//==v1.1.0=================================================================================
	//v1.1.0
	@RequestMapping("/saveImg")
	public String upImg(HttpServletRequest request,HttpSession session,HttpServletResponse response){
		String dsId = request.getParameter("dsId");
		String clnName = request.getParameter("clnName");
		String keyValue = request.getParameter("pkValue");
		String name = (String) request.getAttribute("name");
		String describe =(String)  request.getAttribute("describe");
		String suffix = (String) request.getAttribute("suffix");
		String path = (String) request.getAttribute("path");
		System.out.println("------------");
		System.out.println(dsId);
		System.out.println(clnName);
		System.out.println(name);
		System.out.println(describe);
		System.out.println(suffix);
		System.out.println(path);
		System.out.println("------------");
		SysUploadInfo uploadInfo = new SysUploadInfo();
		uploadInfo.setDsId(dsId);
		uploadInfo.setClnName(clnName);
		uploadInfo.setName(name);
		uploadInfo.setDescribe(describe);
		uploadInfo.setSuffix(suffix);
		uploadInfo.setPath(path);
		uploadInfo.setKeyValue(keyValue);
		try {
			this.uploadService.saveImgPath(uploadInfo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "1";
	}
	
	@RequestMapping("/imgZ")
	public String openImgZone(String dsId,String clnName,String pkValue,HttpServletRequest request,HttpSession session){
		List<Map<String, Object>> imgs = new ArrayList<Map<String, Object>>();
		try {
			imgs = this.uploadService.loadAllImgs(dsId,clnName,pkValue);
			request.setAttribute("pkValue",pkValue);
			request.setAttribute("dsId", dsId);
			request.setAttribute("clnName", clnName);
	//		for (int i = 0; i < 4; i++) {
	//			HashMap<String, String> img = new HashMap<String, String>();
	//			img.put("src", "UploadFiles/testImg_"+i+".jpg");
	//			img.put("title", "测试图片名字_"+i);
	//			if (i == 2) {
	//				img.put("isd", "T");
	//			}
	//			imgs.add(img);
	//		}
		} catch (Exception e) {
			e.printStackTrace();
		}
		request.setAttribute("imgs", imgs);
		
		return "/model/upload/imageZone";
	}
	/**
	 * 加载所有的图片
	 * @param dsId
	 * @param clnName
	 * @param pkValue
	 * @param request
	 * @param session
	 * @return
	 * @author Xuzq
	 * @date 2014-9-22 下午02:45:20
	 */
	@RequestMapping("loadimg")
	@ResponseBody
	public List loadImgs(String dsId,String clnName,String pkValue,HttpServletRequest request,HttpSession session){
		List<Map<String, Object>> imgs = new ArrayList<Map<String, Object>>();
		try {
			imgs = this.uploadService.loadAllImgs(dsId,clnName,pkValue);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return imgs;
	}
	
	/**
	 * 保存文件
	 * @param request
	 * @param session
	 * @param response
	 * @return
	 */
	@RequestMapping("/upFiles")
	public String upFiles(HttpServletRequest request,HttpSession session,HttpServletResponse response){
		String dsId = request.getParameter("dsId");
		String clnName = request.getParameter("clnName");
		String keyValue = request.getParameter("pkValue");
		String suffix = (String) request.getAttribute("suffix");
		String path = (String) request.getAttribute("path");
		String ufileName = (String) request.getAttribute("ufileName");
		SysUploadInfo uploadInfo = new SysUploadInfo();
		uploadInfo.setDsId(dsId);
		uploadInfo.setClnName(clnName);
		uploadInfo.setName(ufileName);//文件描述名
		uploadInfo.setSuffix(suffix);
		uploadInfo.setPath(path);
		uploadInfo.setKeyValue(keyValue);
		uploadInfo.setRequest(request);
		try {
			int flag = 2;//flag = 1 将文件保存到服务器本地     flag = 2 将文件保存到数据库
			if(flag == 2){
				this.uploadService.saveFilesToDb(uploadInfo);
			}else{
				this.uploadService.saveFiles(uploadInfo);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "1";
	}
	
	/**
	 * 获取所有的文件
	 * @param fileList
	 * @param request
	 * @param session
	 * @param response
	 * @return
	 */
	@RequestMapping("/getFiles")
	@ResponseBody
	public  SysFilesList getFileList(SysFilesList fileList,HttpServletRequest request,HttpSession session,HttpServletResponse response){
		List<SysUploadInfo> files = new ArrayList<SysUploadInfo>();
		try {
			fileList = this.uploadService.getFileList(fileList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return fileList;
	}
	
	/**
	 * 删除指定的文件
	 * @param fileList
	 * @param request
	 * @param session
	 * @param response
	 * @return
	 */
	@RequestMapping("/delFile")
	@ResponseBody
	public  boolean delFile(SysUploadInfo delFile,HttpServletRequest request,HttpSession session,HttpServletResponse response){
		boolean flag = false;
		try {
			flag = this.uploadService.delFile(delFile);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return flag;
	}
	
	/**
	 * 下载指定的文件
	 * @param fileList
	 * @param request
	 * @param session
	 * @param {'fileid':id,'dsId':dsId,'clnName':clnName}
	 */
	@RequestMapping("/downFile")
	@ResponseBody
	public String downFile(SysUploadInfo downFile,HttpServletRequest request,HttpSession session,HttpServletResponse response){
		SysUploadInfo downInfo = new SysUploadInfo();
		try {
			downInfo = this.uploadService.downFile(downFile);
			 // 打开文件
			response.setContentType("bin");
			response.setHeader( "Content-Disposition", "attachment;filename=" + new String( downInfo.getName().getBytes("gb2312"), "ISO8859-1" ) + "." + downInfo.getSuffix() ); 
			// 循环取出流中的数据 downInfo.getName()
			response.getOutputStream().write(downInfo.getFileByte());
		} catch (Exception e) {
			e.printStackTrace();
		}
        return "";
	}
	
	@RequestMapping("/weibo")
	public String weiBoPage(String dsId,String clnName,String pkValue,HttpServletRequest request, HttpSession session){
		request.setAttribute("dsId", dsId);
		request.setAttribute("clnName", clnName);
		try {
			if (pkValue == null || "".equals(pkValue)) {
				pkValue = UUID32.newGuid();
			}else{
				request.setAttribute("count",this.uploadService.getWCount(pkValue));
			}
			request.setAttribute("msg", "success");
		} catch (Exception e) {
			request.setAttribute("msg", e.getMessage());
		}
		request.setAttribute("pkValue", pkValue);
		return "/model/forum/forum_weibo";
	}
	
	
	@RequestMapping("/loadWeibo")
	@ResponseBody
	public List<WeiBoObj> loadWeiBo(String pkValue,HttpServletRequest request, HttpSession session){
		List<WeiBoObj>  weibos = new ArrayList<WeiBoObj>();
		try {
			weibos = this.uploadService.loadWeiBo(pkValue);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return weibos;
	}
	
	
	
	

    /**
     * 右键删除
     */
    @RequestMapping("/deletedPictureById")
    @ResponseBody
    public String deletedPictureById(HttpServletRequest request,
        HttpServletResponse response, HttpSession session) {
        return uploadService.deletedPictureById(request, response, session);
    }

	
	
	  // /////////////////////////////////
    /*
     * 2015/5/29 wg 删除临时文件夹下的图片
     */
    @RequestMapping("/delCacheImgs")
    @ResponseBody
    public void deletetemporaryPicture(HttpServletRequest request,
        HttpServletResponse response, HttpSession session) {
        uploadService.deletetemporaryPicture(request, response, session);
    }
	
    

    // /////////////////////////////////
    /*
     * 2015/5/28 wg 从JSP页面获取上传图片存到指定临时文件夹
     */
    @RequestMapping("/uploadPicture")
    @ResponseBody
    public String uploadPicture(
        @RequestParam(value = "file", required = false)
    MultipartFile fileImg, String dsId, HttpServletRequest request,
        HttpServletResponse response, HttpSession session) {
        return uploadService.uploadPicture(fileImg, dsId, request, response,
            session);
    }
}
